<script setup>
import { onMounted, ref } from 'vue';
import router from '@/router';
import loginApi from '@/api/login_api.js';
import { ElMessage, ElForm, ElFormItem, ElInput, ElUpload, ElSelect, ElOption } from 'element-plus';
import lodash from 'lodash';

// 在 index.vue 中添加 provide
import { provide } from 'vue';
// 引入图标组件
import { GobletFull, GobletSquareFull, TrendCharts, User, UserFilled, Lock, Setting, Expand, Fold, SwitchButton } from '@element-plus/icons-vue';


// ========================= 菜单权限核心配置 =========================
// 1. 定义角色-菜单权限映射（key: roleid，value: 允许显示的顶级菜单name列表）
const roleMenuConfig = {
  0: ['信息管理', '用户管理', '管理员管理'], // roleid=0（管理员）：显示所有菜单
  1: ['信息管理'] // roleid=1（用户）：仅显示信息管理
};

// 2. 全量菜单库
const menuData = ref([
  {name: '信息管理', icon: 'GobletFull', children: [
      {name: '用户管理', icon: 'GobletSquareFull', path: "/user"},
      {name: '场地管理', icon: 'TrendCharts', path: "/stadium"},
      {name: '座位管理', icon: 'TrendCharts', path: "/seat"},
      {name: '比赛管理', icon: 'TrendCharts', path: "/match"},
      {name: '订单管理', icon: 'TrendCharts', path: "/order"},
      {name: '抢票结果', icon: 'TrendCharts', path: "/ticketResult"},
    ]},
  {name: '用户管理', icon: 'User', children: [
      {name: '用户列表', icon: 'UserFilled', path: "/user"},
    ]},
  {name: '管理员管理', icon: 'Lock', children: [
      {name: '管理员列表', icon: 'Setting', path: "admin"},
    ]},
]);

// 3. 筛选后的菜单（供模板渲染，随roleid动态更新）
const filteredMenuData = ref([]);


// ========================= 原有变量与方法 =========================
// 1. 修改信息相关变量
const editUserVisible = ref(false);
const userForm = ref({});
const userFormRef = ref(null);

// 2. 重置密码相关变量
const resetPwdVisible = ref(false);
const pwdForm = ref({ oldPwd: '', newPwd: '', confirmPwd: '' });
const pwdFormRef = ref(null);
const pwdRules = ref({
  oldPwd: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需在6-20位之间', trigger: 'blur' }
  ],
  confirmPwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPwd) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 当前登录用户信息（字段调整为roleid）
const loginAdmin = ref({
  name: "未登录",
  roleid: 1, // 关键：用户角色ID，用于菜单筛选，默认普通用户
  uimg: "",
  username: "",
  password: "",
  phone: "",
  email: "",
  gender: ""
});

const activeIndex = ref('1');
const isCollapse = ref(false);


// ========================= 菜单筛选核心方法 =========================
// 根据用户roleid筛选可访问菜单
function filterMenuByRole(roleId) {
  // 1. 获取当前角色允许的顶级菜单名列表（默认显示信息管理）
  const allowedMenuNames = roleMenuConfig[roleId] || ['信息管理'];

  // 2. 递归筛选菜单
  function recursiveFilter(menuList) {
    return menuList.filter(menu => {
      if (allowedMenuNames.includes(menu.name)) {
        if (menu.children && menu.children.length > 0) {
          menu.children = [...menu.children]; // 深拷贝避免修改原数据
        }
        return true;
      }
      return false;
    });
  }

  // 3. 执行筛选并更新筛选后菜单
  filteredMenuData.value = recursiveFilter([...menuData.value]);
}


// ========================= 原有方法（部分修改） =========================
// 页面初始化
onMounted(async () => {
  await getLogin(); // 获取用户信息（含roleid）
});

async function getLogin() {
  const token = localStorage.getItem("token");
  if (!token) {
    router.push('/login');
    return;
  }
  try {
    const res = await loginApi.logininfo();
    loginAdmin.value = res; // 更新用户信息（包含roleid）

    // 新增：将用户信息存储到localStorage
    localStorage.setItem('userInfo', JSON.stringify(res));

    // 关键：用户登录后，根据roleid筛选菜单
    filterMenuByRole(loginAdmin.value.roleid);
  } catch (err) {
    ElMessage.error(err.message || '获取用户信息失败');
    localStorage.removeItem("token");
    localStorage.removeItem("userInfo"); // 移除无效用户信息
    router.push('/login');
  }
}

// 打开修改信息对话框
function handleEditUser() {
  userForm.value = lodash.cloneDeep(loginAdmin.value);
  editUserVisible.value = true;
}

// 提交修改信息
async function submitUserEdit() {
  if (!userForm.value.username) {
    ElMessage.warning('用户名不能为空');
    return;
  }
  try {
    delete userForm.value.password;
    await loginApi.updateUser(userForm.value);
    loginAdmin.value = lodash.cloneDeep(userForm.value);
    ElMessage.success('信息修改成功');
    editUserVisible.value = false;
    // 若修改了角色ID，重新筛选菜单
    filterMenuByRole(loginAdmin.value.roleid);
  } catch (err) {
    ElMessage.error(err.message || '修改失败，请重试');
  }
}

// 打开重置密码对话框
function handleResetPwd() {
  pwdForm.value = { oldPwd: '', newPwd: '', confirmPwd: '' };
  resetPwdVisible.value = true;
}

// 提交密码重置
async function submitPwdReset() {
  if (!pwdFormRef.value) return;
  pwdFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      await loginApi.resetPassword({
        oldPwd: pwdForm.value.oldPwd,
        newPwd: pwdForm.value.newPwd,
        user_id: loginAdmin.value.id
      });
      ElMessage.success('密码重置成功，请重新登录');
      resetPwdVisible.value = false;
      logout();
    } catch (err) {
      ElMessage.error(err.message || '密码重置失败，请检查旧密码是否正确');
      pwdForm.value.oldPwd = '';
    }
  });
}

// 用户下拉菜单点击
function handleSelect(key) {
  if (key === 'logout') logout();
}

// 左侧菜单点击
function handleMenu(key) {
  if (key) router.push(key);
}

// 退出登录
function logout() {
  localStorage.removeItem("token");
  router.push('/login');
}

provide('loginAdmin', loginAdmin); // 将 loginAdmin 提供给子组件

</script>


<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-menu :default-active="activeIndex"
                 class="el-menu-demo"
                 mode="horizontal"
                 :ellipsis="false"
                 background-color="#FF85B3"
                 text-color="#ffffff"
                 active-text-color="#ffffff"
                 @select="handleSelect">

          <el-menu-item index="0">
            <img style="height: 80%" src="@/assets/logo.png" alt="系统logo" />
            <span style="padding-left: 50px; font-size: 24px; color:#ffffff;">羽速抢票-羽毛球比赛抢票系统</span>
          </el-menu-item>
          <div class="flex-grow" />
          <el-sub-menu index="1">
            <template #title>
              <el-avatar :src="loginAdmin.uimg" size="medium">
                <img src="https://xrysitu.oss-cn-beijing.aliyuncs.com/b5a24a51-5db3-40ec-bffc-8999e9cfafc3.png" alt="默认头像" v-if="!loginAdmin.uimg" />
              </el-avatar>
              {{ loginAdmin.username || '未登录' }}
            </template>
            <el-menu-item index="1-1" @click="handleEditUser">修改信息</el-menu-item>
            <el-menu-item index="1-2" @click="handleResetPwd">重置密码</el-menu-item>
            <el-menu-item index="logout">退出
              <el-icon><SwitchButton></SwitchButton></el-icon>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-header>

      <el-container>
        <el-aside :width="isCollapse ? '64px' : '200px'">
          <div style="height: 60px;line-height: 60px; text-align: right; color: #FFF; font-size: 20px; margin-right: 24px;">
            <el-icon @click="isCollapse=!isCollapse">
              <Expand v-if="isCollapse"></Expand>
              <Fold v-else></Fold>
            </el-icon>
          </div>
          <!-- 关键：渲染筛选后的菜单filteredMenuData -->
          <el-menu active-text-color="#ffffff" background-color="#FF99BB"
                   class="el-menu-vertical-demo" default-active="/user"
                   text-color="#ffffff" :collapse="isCollapse" @select="handleMenu">
            <el-sub-menu v-for="(menu, index) in filteredMenuData" :key="index" :index="index.toString()">
              <template #title>
                <component
                    class="icons"
                    :is="menu.icon"
                    style="width: 1em; height: 1em; margin-right: 8px" >
                </component>
                <span>{{ menu.name }}</span>
              </template>
              <el-menu-item v-for="(child, ind) in menu.children" :key="ind" :index="child.path">
                <el-icon><component :is="child.icon"></component></el-icon>
                <span>{{ child.name }}</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>

        <el-main class="main-content">
          <div class="content-wrapper">
            <router-view></router-view>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>

  <!-- 修改信息对话框 -->
  <el-dialog v-model="editUserVisible" title="修改个人信息" width="600px">
    <el-form ref="userFormRef" :model="userForm" label-width="100px">
      <el-form-item label="用户名" required>
        <el-input v-model="userForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="(response) => { userForm.uimg = response.data; }"
        >
          <img
              :src="userForm.uimg ? userForm.uimg : '/src/assets/upload.png'"
              style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover"
              alt="头像"
          />
        </el-upload>
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="userForm.roleid" disabled>
          <el-option label="管理员" value="0" />
          <el-option label="用户" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="userForm.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="userForm.gender" placeholder="请输入性别（男/女）" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="userForm.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="userForm.email" placeholder="请输入邮箱" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editUserVisible = false">取消</el-button>
      <el-button type="primary" @click="submitUserEdit">确认修改</el-button>
    </template>
  </el-dialog>

  <!-- 重置密码对话框 -->
  <el-dialog v-model="resetPwdVisible" title="重置密码" width="400px">
    <el-form
        ref="pwdFormRef"
        :model="pwdForm"
        :rules="pwdRules"
        label-width="100px"
    >
      <el-form-item label="旧密码" prop="oldPwd">
        <el-input
            v-model="pwdForm.oldPwd"
            type="password"
            placeholder="请输入旧密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input
            v-model="pwdForm.newPwd"
            type="password"
            placeholder="请输入新密码"
        />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPwd">
        <el-input
            v-model="pwdForm.confirmPwd"
            type="password"
            placeholder="请再次输入新密码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="resetPwdVisible = false">取消</el-button>
      <el-button type="primary" @click="submitPwdReset">确认重置</el-button>
    </template>
  </el-dialog>
</template>


<style>
.flex-grow {
  flex-grow: 1;
}

.common-layout,
.el-container {
  height: 100%;
}

.el-header {
  --el-header-padding: 0;
  --el-header-height: 80px;
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  padding: var(--el-header-padding);
}

.el-menu--horizontal {
  height: 80px;
}

.el-aside {
  background-color: #FF99BB;
  transition: width 0.3s ease;
}

.el-main {
  padding: 0;
  background-image: url('@/assets/back.png');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  min-height: calc(100vh - 80px);
}

.content-wrapper {
  padding: 20px;
  min-height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 0 10px rgba(255, 105, 180, 0.15);
}

.el-menu {
  border-width: 0px;
}

.el-menu-item {
  font-size: 16px;
}

.el-menu-demo {
  box-shadow: 0 2px 4px rgba(255, 105, 180, 0.25);
}

.el-sub-menu__title {
  font-size: 16px;
}

.icons {
  display: inline-block;
}

/* 粉色主题按钮样式 */
:deep(.el-button--primary) {
  background-color: #FF69B4 !important;
  border-color: #FF69B4 !important;
}

:deep(.el-button--primary:hover) {
  background-color: #FF5CA8 !important;
  border-color: #FF5CA8 !important;
}

/* 对话框标题样式 */
:deep(.el-dialog__title) {
  color: #FF69B4;
  font-weight: 600;
}

/* 菜单选中样式 */
:deep(.el-menu-item.is-active) {
  background-color: #FF69B4 !important;
}

/* 下拉菜单样式 */
:deep(.el-sub-menu .el-menu) {
  background-color: #FFB6C1 !important;
}

:deep(.el-sub-menu .el-menu-item) {
  color: #fff !important;
}

:deep(.el-sub-menu .el-menu-item:hover) {
  background-color: #FF69B4 !important;
}
</style>
